package com.spring.app.processor;

import com.spring.framework.BeanPostProcessor;
import com.spring.framework.BeanProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 切面的模拟实现，通过返回一个代理对象来实现
 * @author yangjian
 */
@BeanProcessor
public class AspectProcessor implements BeanPostProcessor {
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws Exception
	{
		Object proxyInstance;
		if ("orderService".equals(beanName)) {
			System.out.printf("Create a proxy object for bean %s %n", beanName);
			proxyInstance = Proxy.newProxyInstance(AspectProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
				{
					System.out.println("执行切面逻辑 ...");
					return method.invoke(bean, args);
				}
			});
			return proxyInstance;
		} else {
			return bean;
		}
	}
}
